#pragma once

#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace LogModule;
using namespace SocketModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &socket, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, ioservice_t service) : _port(port),
                                                    _listensockptr(std::make_unique<TcpSocket>()),
                                                    _isrunning(false),
                                                    _service(service)
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }

    void start()
    {
        _isrunning = true;
        // while (1)
        // {
        //     sleep(10);
        //     LOG(LogLevel::DEBUG) << "accept success ...";
        // }
        while (_isrunning)
        {
            InetAddr client;
            auto sock = _listensockptr->Accept(&client);
            if (sock == nullptr)
            {                               
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success ...";
            pid_t id = fork();
            if (id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                _listensockptr->close();
                if (fork() > 0)
                {
                    exit(OK);
                }
                _service(sock, client);
                exit(OK);
            }
            else
            {
                sock->close();
                pid_t rid = ::waitpid(rid, nullptr, 0);
                (void)rid;
            }
        }
        _isrunning = false;
    }
    ~TcpServer() {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isrunning;
    ioservice_t _service;
};